//
//  ZRPulishViewController.swift
//  Sina
//
//  Created by 张锐 on 16/3/6.
//  Copyright © 2016年 zhangr. All rights reserved.
//

import UIKit
import AFNetworking
var message  = "我是爸爸..."

class ZRPulishViewController: UIViewController,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()

        setupNav()
        
        setupTextView()
        
        setupToolBar()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBarFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonWriteOnTextView:", name: "emoticonButtonClickNotification", object: nil)
    }
    /// titleLabel
    private lazy var titleLabel : UILabel = {
    
        //设置title
        let titleLabel = UILabel(frame: CGRectMake(0,0,200,44))
        
        titleLabel.numberOfLines = 0
        
        titleLabel.textAlignment = .Center
        
        let textStr = "发布微博\n\(ZRTokenModelView.shareInstance.model?.screen_name ?? "")"
        
        let attribute = NSMutableAttributedString(string: textStr)
        
        attribute.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(18),NSForegroundColorAttributeName : UIColor.orangeColor()], range: NSMakeRange(0, 4))
        
        attribute.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11)], range: NSMakeRange(4, textStr.characters.count - 4))
        
        titleLabel.attributedText = attribute

        return titleLabel
        
    }()
    /// 懒加载textView
    private lazy var textView : ZRTextView = {
    
        let textView = ZRTextView()
        
        textView.message = message
        
        textView.font = UIFont.systemFontOfSize(18)
        
//        // 滑动textView让,键盘消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        return textView
 
    }()
    /// 懒加载toolBar
    private lazy var toolBar : UIToolbar = {
    
        let toolBar = UIToolbar()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var array : [UIBarButtonItem] = [UIBarButtonItem]()
        
        for item in itemSettings{
        
            let button = UIButton(type: UIButtonType.Custom)
            
            button.setImage(UIImage(named:item["imageName"]!), forState: UIControlState.Normal)
            
            let imageName : String = item["imageName"]!
            
            button.setImage(UIImage(named:"\(imageName)_highlighted"), forState: UIControlState.Highlighted)
            
            button.sizeToFit()
            
            if let actionName = item["action"] {
            
                button.addTarget(self, action: Selector(actionName) , forControlEvents: UIControlEvents.TouchUpInside)
            
            }
            
            array.append(UIBarButtonItem(customView: button))
            array.append(UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        
        }
        
        array.removeLast()
        
        toolBar.items = array
        
        return toolBar
    
    }()
    /// 懒加载中间添加图片视图
    lazy var photoView : ZRPublishPhotoView = {
    
        let photoView = ZRPublishPhotoView()
        
        photoView.closure = {[weak self] ()->() in
        
            self!.choosePicture()
            
        }
        
        return photoView
    
    }()
    
    deinit{
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }

    //懒加载emoticonView
    
    lazy var emoticonView = ZREmoticonView(frame: CGRectMake(0,UIScreen.mainScreen().bounds.height - 216,UIScreen.mainScreen().bounds.width,216))
    
 
}

/**
 NAV相关
 */
extension ZRPulishViewController{
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "backButtonClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publishButtonClick")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleLabel
           
    }
    /**
     返回按钮点击
     */
    func backButtonClick(){
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    
    }
    /**
     发布按钮点击
     */
    func publishButtonClick(){
    
        var publishStr : String = ""
        
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (data : [String : AnyObject], range : NSRange, _ ) -> Void in
            
            if let attachment = data["NSAttachment"] as? ZREmoticonAttachment{
            
                publishStr += (attachment.emoticon?.chs)!
            
            }else{
            
            
                publishStr += (self.textView.text as NSString).substringWithRange(range)
            
            }
        }
        
        
            let afn = AFHTTPSessionManager()
            
            let parameters :[String : NSObject] = ["access_token" : ZRTokenModelView.shareInstance.access_token!,"status":publishStr]
            
            afn.POST("https://api.weibo.com/2/statuses/update.json", parameters: parameters, progress: nil, success: { (_, JSON) -> Void in
                
                    print("成功")
                
                    self.backButtonClick()
                
                }, failure: { (_, error) -> Void in
                    
                    print("\(error)")
            })
        
       
    
    }

}
// MARK: - 中间textView相关
extension ZRPulishViewController {

    func setupTextView(){
        
        textView.delegate = self
    
        view.addSubview(textView)
        
        //设置约束
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(view.snp_top)
            
            make.left.equalTo(view.snp_left)
            
            make.right.equalTo(view.snp_right)
            
            make.bottom.equalTo(view.snp_bottom)
            
        }
        
        textView.addSubview(photoView)
        
        photoView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(textView.center)
            
            make.width.equalTo(UIScreen.mainScreen().bounds.width - 20)
            
            make.height.equalTo(UIScreen.mainScreen().bounds.width - 20)
        }
        
        
        
        
    
    }
    
    /**
     文字变化时候的代理方法
     */
    func textViewDidChange(textView: UITextView) {
        
        if textView.hasText(){
        
            self.textView.message = ""
        
        }else{
        
            self.textView.message = "我是爸爸..."
        
        }
        
        textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    /**
     监听表情按钮点击调用方法
     */
    func emoticonWriteOnTextView(not : NSNotification){
    
        //PNG表情上屏
        if let emoticon = not.userInfo!["emoticon"] as? ZREmoticonModel where emoticon.png != nil{
        //之前的attribute
        let beforeAttributeText = NSMutableAttributedString(attributedString: textView.attributedText)
        //弄个附件
        let attachment = ZREmoticonAttachment()
        //附件属性 主要为了发送chs用
        attachment.emoticon = emoticon
        //附件图片路径
        let imagePath = "\(attachment.emoticon!.packagePath!)/\(attachment.emoticon!.png!)"
        //图片上附件
        attachment.image = UIImage(named:imagePath)
        //附件转成attribute可以加入到原来的attribute
        let attribute = NSAttributedString(attachment: attachment)
        //判断现在光标所在处
        let range = textView.selectedRange
        //加入到原来的attribute
        beforeAttributeText.insertAttributedString(attribute, atIndex: range.location)
        //textViewattribute赋值回来
        textView.attributedText = beforeAttributeText
        //光标后移
        textView.selectedRange = NSMakeRange(range.location + 1, 0)
        }
        
        //emoji表情上屏
        if let emoticon = not.userInfo!["emoticon"] as? ZREmoticonModel where emoticon.emoji != nil {
        
            let beforeAttributeText = NSMutableAttributedString(attributedString: textView.attributedText)
            
            let attribute = NSAttributedString(string: emoticon.emoji!)
            
            let range = textView.selectedRange
            
            beforeAttributeText.insertAttributedString(attribute, atIndex: range.location)
            
            textView.attributedText = beforeAttributeText
            
            textView.selectedRange = NSMakeRange(range.location + (emoticon.emoji! as NSString).length , 0)
            
        }
        
    }

}
// MARK: - toolBar相关
extension ZRPulishViewController{

    func setupToolBar(){
    
        view.addSubview(toolBar)
        
        //设置约束
        
        toolBar.snp_makeConstraints { (make) -> Void in
            
//            make.top.equalTo(textView.snp_bottom)
            
            make.left.equalTo(view.snp_left)
            
            make.right.equalTo(view.snp_right)
            
            make.bottom.equalTo(view.snp_bottom)
            
            make.height.equalTo(44)
            
        }
        
    
    }
    
    func changeToolBarFrame(notification:NSNotification)->(){
    
        /*
        Optional([UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        */
        /*
        Optional([UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 409}, {375, 258}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 796}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 667}, {375, 258}}, UIKeyboardAnimationDurationUserInfoKey: 0.25, UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 538}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
       
        */
    
        if let rect = notification.userInfo{
        
            let endY = rect[UIKeyboardFrameEndUserInfoKey]?.CGRectValue.origin.y
            
            if endY == UIScreen.mainScreen().bounds.height{
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.toolBar.transform = CGAffineTransformIdentity
                })

            }else{
//
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.toolBar.transform = CGAffineTransformMakeTranslation(0, -(UIScreen.mainScreen().bounds.height - endY!))
                })
                

            }
        }
    
    }
    /**
     选择图片按钮点击事件
     */
    func choosePicture(){
        
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            let picker = UIImagePickerController()
            
            picker.sourceType = .PhotoLibrary
            
            picker.delegate = self
            
            presentViewController(picker, animated: true, completion: { () -> Void in
                
            })
        
        
        }
    
    }
    /**
     放入表情点击事件
     */
    func inputEmoticon(){
        
        //切换inputView
        textView.resignFirstResponder()
        
        if textView.inputView == nil{
        
            textView.inputView = emoticonView
        
        }else{
        
            textView.inputView = nil
            
        
        }
        
        textView.becomeFirstResponder()
    
    }

}
// MARK: - UIImagePickerdelegate
extension ZRPulishViewController{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
       
        photoView.addImage(image)
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
        
    }
    


}


